const Router = require('@koa/router');
const query = require('./query')
const { sign } = require('./helper')

const router = new Router();

router.get('/login', async ctx => ctx.render('login.html')) // 登录
router.get('/', async ctx => ctx.render('index.html')) // 商品列表页
router.get('/detail/:id', async ctx => ctx.render('detail.html')) // 商品详情页
router.get('/carts', async ctx => ctx.render('carts.html')) // 购物车列表页

// 登录
router.post('/api/login', async ctx => {
  // 参数
  console.log('---------', ctx.request.body);
  const { username, password } = ctx.request.body;
  // 逻辑
  let sql = ` select * from users where username = '${username}' and password = '${password}'`
  const res = await query(sql)

  // 返回
  if (res.length) {
    const token = sign({ id: res[0].id });
    ctx.cookies.set('token', token)
    ctx.body = {
      code: 200,
      msg: '登录成功'
    }
  } else {
    ctx.body = {
      code: 400,
      msg: '登录失败'
    }
  }
})

// 商品列表
router.get('/api/goodsList', async (ctx, next) => {
  const { name, currentPage, pageSize } = ctx.query;
  let sql = `select * from goods where 1=1 `
  if (name) sql += ` and name like '%${name}%' ` // 模糊搜索

  // 拿到搜索的合计
  const arrList = await query(sql)
  const total = arrList.length;

  // 加上分面的查询
  if (currentPage && pageSize) sql += ` limit ${pageSize} offset ${(currentPage - 1) * pageSize} ` // 分页

  const res = await query(sql)

  ctx.body = {
    code: 200,
    msg: '商品列表获取成功',
    data: { res, total, pageSize, currentPage }
  }
});

// 商品详情
router.get('/api/goodsDetail/:id', async (ctx, next) => {
  // 参数
  const { id } = ctx.params;
  // 逻辑
  let sql = `select * from goods where id=${id}`
  const res = await query(sql)
  // 返回
  if (res.length) {
    ctx.body = {
      code: 200,
      msg: '成功',
      data: res[0]
    }
  } else {
    ctx.body = {
      code: 400,
      msg: '失败',
    }
  }

});

// 添加购物车
router.post('/api/addCart', async ctx => {
  //参数
  const { gid } = ctx.request.body;
  const userid = ctx.userid;
  //逻辑
  const arrList = await query(`select * from carts where uid=${userid} and gid=${gid} and status='购物车' `)
  let sql;
  if (arrList.length) {
    sql = ` update carts set num=${++arrList[0].num} where id=${arrList[0].id}`
  } else {
    sql = ` insert into carts ( uid, gid, num, status ) values ( ${userid}, ${gid}, ${1}, '${"购物车"}' )`
  }
  const res = await query(sql)
  //返回
  if (res.affectedRows) {
    ctx.body = {
      code: 200,
      msg: '添加购物车成功'
    }
  } else {
    ctx.body = {
      code: 400,
      msg: '添加购物车失败'
    }
  }
})

// 当前用户购物车列表
router.get('/api/cartList', async ctx => {
  //参数
  const userid = ctx.userid;
  //逻辑
  let sql = `select
              users.username,
              users.nickname,
              carts.*,
              goods.name,
              goods.price 
            from
              carts
              left join users on users.id = carts.uid
              left join goods on goods.id = carts.gid 
            where
              users.id = ${userid} and carts.status='购物车' `

  const res = await query(sql);

  //返回
  if (res.length) {
    ctx.body = {
      code: 200,
      msg: '获取当前用户购物车列表成功',
      data: res
    }
  } else {
    ctx.body = {
      code: 204,
      msg: '获取当前用户购物车列表成功, 但列表为空!',
      data: res // [] 空数组
    }
  }
})


module.exports = router;